package com.metacube.metaconnect.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.metacube.metaconnect.Service.UserInformationService;

/**
 * Servlet implementation class ValidateActivationCodeServlet
 */
public class ValidateActivationCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ValidateActivationCodeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * validates the activation code while activation of user
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int activationCode = 0;
		try {
			activationCode = Integer.parseInt(request
					.getParameter("activationCode"));
		} catch (Exception e) {
			response.sendRedirect("index.jsp");
		}

		String emailId = new UserInformationService()
				.getEmailId(activationCode);

		if (emailId == null) {
			response.sendRedirect("index.jsp");
		}
		if (emailId.startsWith("active,")) {
			request.getSession().setAttribute("emailId", emailId.split(",")[1]);
			response.sendRedirect("home.jsp");
		} else if (emailId.equals("invalid activation code")) {
			response.sendRedirect("index.jsp");
		} else {
			request.getSession().setAttribute("signupstep1", emailId);
			request.getRequestDispatcher("SignUpStep1.jsp").forward(request,
					response);
		}
	}
}
